// Icons
var defaultIcon = './img/park_blue_26x26.png';	
var fewVacantIcon = './img/park_yellow_26x26.png';
var fullIcon =  './img/park_red_26x26.png';
var showVacant = 0.20; // Number of vacant park spaces necessary for icon to be shown 

var markers = new Array(); // Saving markers for later

var infowindow;	// Info window on each parking location (google map)

var map;	// The google map
var meLatLng;	// Users position 
var currentLat = null;
var currentLng = null;
var markerUser = null; // Users marker on google map
var keepMapInCenter = new Boolean(); // true makes the map always show all items, false not...
var gpsStatusIcon = null; // Icon showing GPS status

var currentParkData;	// Current data from the park locations

var timerId = null;
function updateGpsTimer(startOrNot) {
	if(startOrNot==1) {
		if(timerId!=null) {
			clearInterval(timerId);
		}
		setGpsIcon('gstart');
		getCurrentLocation();
		timerId = setInterval(getCurrentLocation,10000);
	} else {
		setGpsIcon('gno');
		if(timerId != null) {
			clearInterval(timerId);
		}
		updateGPSPos(null,null);
	}
}

function setGpsIcon(icon) {
	if(gpsStatusIcon != null) {
		$("#gpsstat").attr("src","img/" + icon + ".png");
	}
}


function mapInits() {
	// Check if the gps icon is defined
	gpsStatusIcon = document.getElementById("gpsstat");
}

function getCurrentLocation() {
	navigator.geolocation.getCurrentPosition(handlePos,handle_errors);
}

function handlePos(position) {
	var lat =  position.coords.latitude;
	var lon =  position.coords.longitude;
	setGpsIcon('gok');
	updateGPSPos(lat,lon);
}

function handle_errors(error)
{
	var retStr;
	switch(error.code)
	{
		case error.PERMISSION_DENIED: retStr = "Tilgang ikke gitt for posisjonsdata...";
		break;
		case error.POSITION_UNAVAILABLE: retStr = "Kunne ikke finne posisjonen";
		break;
		case error.TIMEOUT: retStr = "Timeout ved henting av posisjonsdata";
		break;
		default: retStr = "Ukjent feil";
		break;
	}
	updateGpsTimer(0); // reset timer, but keep setting 
	alert(retStr);
	setGpsIcon('gerr');
	// Error - turn off the gps flag and save
	toggleGpsShow();
}
// Update current position with gps pos
function updateGPSPos(lat,lng) {
	currentLat = lat;
	currentLng = lng;
	
	setUserLocation();
	if(SETTINGS_meCenter==1) {
		centerMe();
	}
//	if(keepMapInCenter) {
//		setMapCenter();
//	}
}

// Sets the map centered
function keepMapCentered(yesOrNo) {
	keepMapInCenter = yesOrNo;
}

// Show the map
function showMap() {
	    

	// Placing the user on Puddefjordsbroen as default, this becomes center of map	
	meLatLng = new google.maps.LatLng(60.383719,5.316997);
    
	var myOptions = {
      zoom: 14,
      center: meLatLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoomControlOptions: {
          position: google.maps.ControlPosition.LEFT_CENTER
      }
    };

	// The map
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	// Infowindow on map
	infowindow = new google.maps.InfoWindow();
	
    setUserLocation();
	setMapCenter();
	document.getElementById("parkIconFilterValue").innerHTML = SETTINGS_parkIconFilter;
}

function setParkLocations(){
	for (i in parkLocation){
		parkLoc = parkLocation[i]
		var lat = parkLoc[1];
		var lon = parkLoc[2];
		var position = new google.maps.LatLng(lat,lon);
		var title = parkLoc[3];

		function createMarker(position,title,icon,html) {
	        var marker = new google.maps.Marker({ position: position, title: title, icon: icon });
	        google.maps.event.addListener(marker, "click", function() {
	          //marker.openInfoWindowHtml(html);
	          //marker.setContent(html);
	        	infowindow.setContent(html);
	        	infowindow.open(map, this);
	        });
	        return marker;
	      }

		var contentString = '<div id="pcontent" class="thebox">'+	
		'<h1>'+parkLoc[0]+'</h1>'+
		 	'<h2>'+parkLoc[3]+'</h2>'+
		    '<div id="bodyContent">'+
		    '<p>'+parkData[parkLoc[0]][1]+' ledige av totalt '+parkData[parkLoc[0]][2]+' ledige</p>'+
		    '<img src="http://gremlin.stud.aitel.hist.no/~ronna/prosjekt/getimage.php?w=100&h=5&l='+parkData[parkLoc[0]][1]+'&t='+parkData[parkLoc[0]][2]+'"/ border="0">' +
		    '<p><a href="#">se statistikker</a></p>'+
		    '</div>';

		markers[i].setMap(null); // remove old icon
		markers[i]= createMarker(position,title,defaultIcon, contentString);
		markers[i].setMap(map);
	}
	filterParkIcons(SETTINGS_parkIconFilter);
}		

// Set the user marker on the map
function setUserLocation(){	
	// Only if current location is known.
	if(currentLat != null && currentLng != null) {
		meLatLng = new google.maps.LatLng(currentLat,currentLng);
		if(markerUser == null) {
			// If not created before - create marker
			markerUser = new google.maps.Marker({ position: meLatLng, title:"Du er her"} );
		} else {
			markerUser.setPosition(meLatLng);
		} 
		markerUser.setMap(map);
	} else {
		// remove marker on map - keep as variable 
		if(markerUser != null) {
			markerUser.setMap(null);
		}
	}
}	

function getIndicatorIcon(vacantPark, totalPark){
	vacant = parseFloat(vacantPark);
	total = parseFloat(totalPark);
	if (vacant == 0)
		return fullIcon;
	else if (vacant/total < showVacant)
		return fewVacantIcon;
	else
		return defaultIcon;		
}

// Sets maps center 
function setMapCenter() {
	var bounds = new google.maps.LatLngBounds();
	if (parkLocation.length>1){				
		// loop through and find the outer boundaries
		for ( i=0 ; i<parkLocation.length ; i++ ) {		
			bounds.extend(new google.maps.LatLng(parkLocation[i][1],parkLocation[i][2]));
		}
	}
	if(currentLat != null && currentLng != null) {
		bounds.extend(meLatLng);
	}
	map.setCenter(bounds.getCenter());
}

// Put me in the center of the map
function centerMe() {
	if(SETTINGS_meCenter==1) {
		var bounds = new google.maps.LatLngBounds();
		if(currentLat != null && currentLng != null) {
			bounds.extend(meLatLng);
			map.setCenter(bounds.getCenter());
		}
	}
}
// Center og zoom alt
function centerAll() {
	var bounds = new google.maps.LatLngBounds();
	if (parkLocation.length>1){				
		// loop through and find the outer boundaries
		for ( i=0 ; i<parkLocation.length ; i++ ) {		
			bounds.extend(new google.maps.LatLng(parkLocation[i][1],parkLocation[i][2]));
		}
	}
	if(currentLat != null && currentLng != null) {
		bounds.extend(meLatLng);
	}

	map.setCenter( bounds.getCenter( ));
	map.fitBounds (bounds);
}

function updateIcons(data){
	console.log("*** updateIcons "+data);

	currentParkData = data; // saving last update for later use in updateParkIconFilterValue()
	var parkArray = data.trim().split(";");	
	// For each location put correct icon
	for(i=0;i<parkLocation.length;i++){
		var parkLocData = parkArray[i].trim().split(",");	
		
		// Fetching right icon to shown depending on data
		icon = getIndicatorIcon(parkLocData[1],parkLocData[2]);
	
			var parkLoc = parkLocation[i]
			var lat = parkLoc[1];
			var lon = parkLoc[2];
			var position = new google.maps.LatLng(lat,lon);
			var title = parkLoc[3];

			function createMarker(position,title,icon,html) {
		        var marker = new google.maps.Marker({ position: position, title: title, icon: icon });
		        google.maps.event.addListener(marker, "click", function() {
		        	infowindow.setContent(html);
		        	infowindow.open(map, this);
		        });
		        return marker;
		      }

			var contentString = "";
			var infoArray = getParkInfo(parkLoc[0]);
			
			if(infoArray != null) {
				contentString = '<div id="pcontent" class="thebox">'+	
				'<h2>'+parkLoc[0]+'</h2>'+
				 	'<h3>'+parkLoc[3]+'</h3>'+
				    '<div id="bodyContent">'+
				    '<p>'+infoArray[1]+' ledige av totalt '+infoArray[2]+' ledige</p>'+
				    '<img src="http://stud.aitel.hist.no/~ronna/prosjekt/getimage.php?w=100&h=5&l='+infoArray[1]+'&t='+infoArray[2]+'"/ border="0">' +
				    '<p><a href="#">se statistikker</a></p>'+
				    '</div>';
			} else  {
				contentString = '<div id="pcontent" class="thebox">'+	
				'<h2>'+parkLoc[0]+'</h2>'+
				 	'<h3>'+parkLoc[3]+'</h3>'+
				    '<div id="bodyContent">'+
				    '<p>Kommer etterhvert...</p>'+
				    '</div>';
			}

			//TODO: Hva er dette ?
			if (markers[i]) {
				markers[i].setMap(null); 
			}
			
			markers[i]= createMarker(position,title,icon, contentString);
			markers[i].setMap(map);
	}
	filterParkIcons(SETTINGS_parkIconFilter);
}

function showSettingsPane() {
	$('#settingsPane').slideToggle();
	$('#showSettingsPane').hide();
	$('#hideSettingsPane').show();
	
}

function hideSettingsPane() {
	$('#settingsPane').slideToggle();
	$('#showSettingsPane').show();
	$('#hideSettingsPane').hide();
}

function showTestPane() {
	$('#testPane').slideToggle();
	$('#showTestPane').hide();
	$('#hideTestPane').show();
	
}

function hideTestPane() {
	$('#testPane').slideToggle();
	$('#hideTestPane').show();
	$('#showTestPane').hide();
}

function updateParkIconFilterValue(newValue)
{
	SETTINGS_parkIconFilter=newValue;
	saveProperties();
	filterParkIcons(newValue);
}

function filterParkIcons(newValue){
	if(markers) {
		if (SETTINGS_parkIconFilterFlag==0) {
			for (i=0;i<markers.length;i++){
				markers[i].setVisible(true);
			}
		}
		else
		{
			// check if availible spaces are smaller than filter value
			var parkArray = currentParkData.trim().split(";");	
			for(i=0;i<parkLocation.length;i++){
				var parkLocData = parkArray[i].trim().split(",");			
				if (parseInt(parkLocData[1]) > newValue){
					markers[i].setVisible(true);
				} else {
					markers[i].setVisible(false);
				}
			}
		}
	}
}

function checkboxFilterClicked() {
	SETTINGS_parkIconFilterFlag = SETTINGS_parkIconFilterFlag==0?1:0;
   
	if (SETTINGS_parkIconFilterFlag==1)
		$('#filterSlider').show();
	else
		$('#filterSlider').hide();
	filterParkIcons(SETTINGS_parkIconFilter);
	saveProperties();
}

function setCheckboxFilter(value){
	if (value==1) {
		$('#filterFlagCheckBox').attr('checked', true);
		$('#filterSlider').show();
	}
	else {
		$('#filterFlagCheckBox').attr('checked', false);
		$('#filterSlider').hide();
	}	
}